/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.haiberg.osgi.bundle.reportservice;

import com.haiberg.osgi.bundle.reportservice.utils.Constants;
import com.haiberg.osgi.bundle.reportservice.utils.ReportUtils;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author gyue
 */
public class ReportFileHandler {
    private String reportName;
    private String appUsername;
    
    public ReportFileHandler(){
    
    }
    
    public boolean addReport(File file){
        boolean isValid = validate();
        if(isValid){
            String reportPath = ReportUtils.getReportAbsolutePath(this.reportName, this.appUsername);
            File diskReportFile = new File(reportPath);
            if(diskReportFile.exists()){
                return false;
            }else{
                checkParentDirectory();
                try {
                    FileUtils.copyFile(file, diskReportFile);
                } catch (IOException ex) {
                    Logger.getLogger(ReportFileHandler.class.getName()).log(Level.SEVERE, null, ex);
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    
    public boolean deleteReport(){
        boolean isValid = validate();
        if(isValid){
            String reportPath = ReportUtils.getReportAbsolutePath(this.reportName, this.appUsername);
            File diskReportFile = new File(reportPath);
            if(diskReportFile.exists()){
                return diskReportFile.delete();
            }
        }
        return false;
    }
    
    private void checkParentDirectory(){
        String parentDirPath = ReportUtils.getReportDirectoryPath(this.appUsername);
        File parentDir = new File(parentDirPath);
        if(!parentDir.exists()){
            parentDir.mkdirs();
        }
    }
    
    private boolean validate(){
       if(StringUtils.isNotBlank(reportName) &&
               reportName.endsWith(".rpt")){
           if(StringUtils.isBlank(appUsername)){
               this.setAppUsername(Constants.DEFAULT_APP_USERNAME_STRING);
           }
           return true;
       }
       return false; 
    }

    /**
     * @param reportName the reportName to set
     */
    public void setReportName(String reportName) {
        this.reportName = reportName;
    }

    /**
     * @param appUsername the appUsername to set
     */
    public void setAppUsername(String appUsername) {
        this.appUsername = appUsername;
    }

    
}
